app.controller('AppCtrl',function($scope,$ionicLoading,BaseService,$rootScope,$ionicHistory,appFactory,$ionicModal,
                                  $state,$cordovaBarcodeScanner,$cordovaInAppBrowser,$cordovaDevice,$cordovaGeolocation,Push,CheckVersion,$ionicPlatform,$cordovaAppVersion){

    var options = {
        location: 'no',
        clearcache: 'yes',
        toolbar: 'no'
    };

    $scope.isAdmin = false;

    var checkAdmin = function(){
        var urole = appFactory.getUserInfo().user.urole;
        if (urole == 2){
            $scope.isAdmin = true;
        }

    }

        $ionicPlatform.ready(function(){
            $scope.checkForUpdates();
            $ionicModal.fromTemplateUrl('templates/login.html', {
                scope: $scope
            }).then(function(modal) {
                $scope.modal = modal;
                if(!appFactory.isLogin()){
                    modal.show();
                }else{
                    Push.setAlias(appFactory.getUserInfo().uid);
                }
            });
        });

        $scope.loginData = {username:"",password:"",namenull:true,pwdnull:true};
        /**
         * 登录
         */
        $scope.doLogin = function(){
            $ionicLoading.show({});
            appFactory.doLogin($scope.loginData.username, $scope.loginData.password).then(function (res) {
                $ionicLoading.hide();
                //checkAdmin();
                Push.setAlias(appFactory.getUserInfo().uid);
                switch (parseInt(res.query2.code)){
                    case 0:
                        $scope.modal.hide();
                        window.location.reload();
                        break;
                    case 1:
                        alert("账号或密码错误");
                        break;
                    case 2:
                        alert("系统错误");
                        break;
                }
            });
        };
    $scope.showRanking = function() {
        //跳转至系统的浏览器中打开
        var link = 'http://61.147.75.91/demo/reportJsp/showReport.jsp?raq=/lhb.raq';
        $cordovaInAppBrowser.open(link, '_system', options).then(function(event) {}).catch(function(event) {});

    };

    $scope.showRankingPS = function() {
        //跳转至系统的浏览器中打开
        var link = 'http://61.147.75.91/demo/reportJsp/showReport.jsp?raq=/pstc.raq';
        $cordovaInAppBrowser.open(link, '_system', options).then(function(event) {}).catch(function(event) {});

    };

    $scope.showRankingYX = function() {
        //跳转至系统的浏览器中打开
        var link = 'http://61.147.75.91/demo/reportJsp/showReport.jsp?raq=/yxtc.raq';
        $cordovaInAppBrowser.open(link, '_system', options).then(function(event) {}).catch(function(event) {});

    };

    //用户收账明细
    $scope.showRanking1 = function() {
        //跳转至系统的浏览器中打开
        var link = 'http://61.147.75.91/demo/reportJsp/showReport.jsp?raq=/wlyhsc.raq';
        $cordovaInAppBrowser.open(link, '_system', options).then(function(event) {}).catch(function(event) {});

    };
    //分区收账明细
    $scope.showRanking2 = function() {
        //跳转至系统的浏览器中打开
        var link = 'http://61.147.75.91/demo/reportJsp/showReport.jsp?raq=/wlfqsc.raq';
        $cordovaInAppBrowser.open(link, '_system', options).then(function(event) {}).catch(function(event) {});
    };

    $scope.checkForUpdates = function() {

        //跳转至系统的浏览器中打开

        var platform = $cordovaDevice.getPlatform();
        var checkCallback = function(build){
            //alert(build);
            checkAdmin();
            CheckVersion.checkUpdate(build).then(function(downloadUrl){

                if(!confirm('有新版本更新,是否前往更新?')){
                    return false;
                }
                var link = ('iOS' == platform)?downloadUrl.ios:downloadUrl.android;
                $cordovaInAppBrowser.open(link, '_system', options).then(function(event) {}).catch(function(event) {});
            }).catch(function(err){
                alert('当前已是最新版本~');
            });
        };
        if('iOS' == platform){
            $cordovaAppVersion.getVersionCode().then(checkCallback);
        }else{
            $cordovaAppVersion.getVersionNumber().then(checkCallback);
        }
    };
});



app.controller('TakeCtrl', function($scope,$cordovaBarcodeScanner,BaseService,appFactory,$cordovaGeolocation) {
    var posOptions = {timeout: 10000, enableHighAccuracy: false};
    $scope.getPackage = function(event,o,index){
        event = event ? event : window.event;
        var obj = event.srcElement ? event.srcElement : event.target;
        obj.disabled=true;
        if(confirm("请仔细核对订单信息是否正确，确认订单并领单")===true){
            $scope.rush(o,index);
        }else{
            obj.disabled=false;
            return ;
        }
    }
    $scope.rush = function(o,index){
        //更新订单状态，并且移除调该订单
        $scope.canRush = 0;
        var oid = o.get("orderid");
        var storage = window.localStorage;
        var uid = storage.getItem("uid");
        if (oid){
            var Order = AV.Object.extend("Order");
            var orderQuery = new AV.Query(Order);
            orderQuery.equalTo('orderid',oid);
            orderQuery.first().then(function(res){
                $cordovaGeolocation
                    .getCurrentPosition(posOptions)
                    .then(function (position) {
                        var lat  = position.coords.latitude;
                        var long = position.coords.longitude;
                        BaseService.barscanHandle(uid,oid,long,lat).then(function(d){
                            alert(d.msg);
                        }).catch(function(err){
                            alert(err);
                        });
                    }, function(err) {
                        alert("定位失败，请开启定位功能！");
                    });
            }).catch(function(err){
                alert("没有获取到订单编号！");
            });
        }else{
            alert("没有获取到订单编号！");
        }
    }

    $scope.getOrdersArray = function(mhOid){
        if(mhOid===undefined || mhOid.length<6){
            alert("请输入至少6位连续的订单编号");
            $scope.$broadcast('scroll.refreshComplete');
            return;
        }
        var Order = AV.Object.extend("Order");
        async.waterfall([
            function(callback){
                var orderQuery = new AV.Query(Order);
                var ORDER_STATUS = [4000,7000];
                orderQuery.containedIn('status',ORDER_STATUS);
                orderQuery.limit(10);
                orderQuery.contains("orderid",mhOid+'');
                orderQuery.addDescending("bookdate");
                orderQuery.addDescending("paytime");
                orderQuery.find().then(function(res){
                    $scope.$apply(function(){
                        $scope.ordersArray = res;
                        callback(null,$scope.ordersArray);
                    });
                }).catch(function(err){
                    console.log(err);
                    callback(err);
                }).finally(function(){
                    $scope.$broadcast('scroll.refreshComplete');
                });
            },
        ],function(err,result){
            if(err){
                console.log(err);
            }else{
                console.log("OK");
            }
        });
    }


    $scope.barscan = function(){
        $cordovaBarcodeScanner
            .scan()
            .then(function(barcodeData) {
                var cancelled = barcodeData.cancelled;
                var result = JSON.parse(barcodeData.text);
                if(!cancelled){
                    var oid = result.OID;
                    var storage = window.localStorage;
                    var uid = storage.getItem("uid");
                    if (oid){
                        var Order = AV.Object.extend("Order");
                        var orderQuery = new AV.Query(Order);
                        orderQuery.equalTo('orderid',oid);
                        orderQuery.first().then(function(res){
                            $cordovaGeolocation
                                .getCurrentPosition(posOptions)
                                .then(function (position) {
                                    var lat  = position.coords.latitude;
                                    var long = position.coords.longitude;
                                    BaseService.barscanHandle(uid,oid,long,lat).then(function(res){
                                        var r = confirm(res.msg + "\r\n是否继续扫码!");
                                        if (r == true) {
                                            $scope.barscan();
                                        }
                                    }).catch(function(err){
                                        var r = confirm(res.msg + "\r\n是否继续扫码!");
                                        if (r == true) {
                                            $scope.barscan();
                                        }
                                    });
                                }, function(err) {
                                    alert("定位失败，请开启定位功能！");
                                });
                            /*BaseService.barscanHandle(uid, oid).then(function (res) {
                                var r = confirm(res.msg + "\r\n是否继续扫码!");
                                if (r == true) {
                                    $scope.barscan();
                                }
                            }).catch(function (err) {
                                var r = confirm(res.msg + "\r\n是否继续扫码!");
                                if (r == true) {
                                    $scope.barscan();
                                }
                            });*/
                        }).catch(function(err){
                            var r=confirm("没有扫描到正确的订单信息!\r\n是否继续扫码!");
                            if (r==true) {
                                $scope.barscan();
                            }
                        });
                    }else{
                        var r=confirm("没有扫描到正确的订单信息!\r\n是否继续扫码!");
                        if (r==true) {
                            $scope.barscan();
                        }
                    }
                }else{
                    alert('扫描异常或退出扫描');
                }
            }, function(error) {
                // An error occurred
            });
    };
})

app.controller('TasksCtrl', function($scope, Tasks) {


  $scope.tasks = Tasks.all();
  $scope.remove = function(task) {
    Tasks.remove(task);
  };
})

app.controller('TaskDetailCtrl', function($scope, $stateParams, Tasks) {
  $scope.chat = Tasks.get($stateParams.taskId);
})

app.controller('SellCtrl', function($scope) {
      alert('下营销单');
    })
app.controller('SettingCtrl', function($scope) {
    $scope.user = {}
    $scope.accountInit=function(){
        $scope.user.name='zhangshiming';
        $scope.$broadcast('scroll.refreshComplete');
    }
    $scope.accountInit();
    });
